//
//  JCOrderListViewController.m
//  ERP
//
//  Created by QA on 15/10/28.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "JCOrderListViewController.h"
#import "CustomBadge.h"

#import "MJRefresh.h"
#import "OMOrderListViewCell.h"
#import "OMOrderDetailsViewController.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"

#import "OMCreateOrderViewController.h"
#import "OMLogisticsInfoViewController.h"
#import "SearchOrderViewController.h"
#import "SearchTextTimeViewController.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"


@interface JCOrderListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *searchListData;
@property (assign, nonatomic) NSInteger segmentActionState;

@property (strong, nonatomic) NSString *searchText;
@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchStopTime;

@end

@implementation JCOrderListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"订单列表"];
        
        //设置搜索按钮
        UIButton* righButtont= [UIButton buttonWithType:UIButtonTypeCustom];
        righButtont.frame = CGRectMake(0, 0, 44, 44);
        [righButtont setImage:[UIImage imageNamed:@"home_nav_left_serch"] forState:UIControlStateNormal];
        [righButtont addTarget:self action:@selector(searchChargeInSelector:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:righButtont];
    }
    return self;
}

- (id)initWithAuditState:(NSInteger)orderState
{
    self = [super init];
    if(self){
        //@审核状态（0未审核，1已审核, 2已拒绝，4待接单）
        if(orderState == 0) [self setTitle:@"待审核订单"];
        if(orderState == 1) [self setTitle:@"历史订单"];
        if(orderState == 2) [self setTitle:@"已拒绝订单"];
        self.segmentActionState = orderState;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.searchListData = [NSMutableArray array];
    self.searchText = @"";
    self.searchStartTime = @"";
    self.searchStopTime = @"";
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self.segmentedControl setTintColor:ThemeColorBlue];
    [self.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark -
#pragma mark IBAction

- (void)searchChargeInSelector:(id)sender
{
    //搜索订单
    SearchTextTimeViewController *view = [[SearchTextTimeViewController alloc] init];
    view.backResultDelagate = self;
    view.key = @"SerachOrder";
    [self.navigationController pushViewController:view animated:YES];
}

#pragma make - Station Notification

-(void)updateStationNotification:(ModuleAuthorityEntity*)model
{
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self headerRereshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkExternalDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    NSNumber *DDZT = [NSNumber numberWithInteger:self.segmentActionState];
    
    //@审核状态（0未审核，1已审核, 2已拒绝，4待接单）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"DDGL_DD_LIST_NB_SEARCH"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"订单状态" value:DDZT];
    [content addParameterKey:@"检索条件" value:_searchText];
    [content addParameterKey:@"起始时间" value:_searchStartTime];
    [content addParameterKey:@"截止时间" value:_searchStopTime];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>=1){
            firstArray = [result.resultArray firstObject];
        }
        
        //显示数据处理
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
            
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无订单" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkExternalDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkExternalDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.resultData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"OMOrderListViewCell";
    OMOrderListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[OMOrderListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne index:indexPath.row];
    
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.section];
    if(indexPath.row == 0){
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell.orderNumLabel.text = [itemData objectFormatStringForKey:@"订单编号" defaults:@"未知"];
        cell.orderStateLabel.text = [itemData objectFormatStringForKey:@"订单状态" defaults:@"未知"];
        //@订单状态（0未审核，1已审核,  2已拒绝）
        NSInteger sfsh = [itemData objectFormatIntegerForKey:@"DDZT"];
        if (sfsh == 0){
            cell.orderStateLabel.textColor = [UIColorDispose colorWithHexString:@"f8b442"];
        } else if (sfsh == 1){
            cell.orderStateLabel.textColor = ThemeColorBlue;
        } else {
            cell.orderStateLabel.textColor = [UIColorDispose colorWithHexString:@"f8645a"];
        }
        
        //订单是否已读
        NSInteger wbdd = [itemData objectFormatIntegerForKey:@"数据来源"];
        if([itemData objectFormatIntegerForKey:@"isRead"] >= 1){
            NSString *sjly = (wbdd == 3) ? @"[外部] %@" : @"%@";
            cell.iconRead.hidden = YES;
            cell.orderNumLabel.text = [itemData objectFormatStringForKey:@"订单编号"  format:sjly defaults:@"未知"];
        } else {
            NSString *sjly = (wbdd == 3) ? @"        [外部] %@" : @"        %@";
            cell.iconRead.hidden = NO;
            cell.orderNumLabel.text = [itemData objectFormatStringForKey:@"订单编号" format:sjly defaults:@"       未知"];
        }
        
    } else if (indexPath.row == 1) {
        //订单信息设置
        cell.orderNameLabel.text = [itemData objectFormatStringForKey:@"工程名称" defaults:@"未知"];
        cell.castingPartsLabel.text = [itemData objectFormatStringForKey:@"施工部位" defaults:@"未知"];
        cell.openTimeLabel.text = [itemData objectFormatStringForKey:@"计划开盘时间" defaults:@"未知"];
        cell.tldLabel.text = [itemData objectFormatStringForKey:@"坍落度" defaults:@"未知"];
        cell.qddjLabel.text = [itemData objectFormatStringForKey:@"完整砼强度" defaults:@"未知"];
        cell.pumpInfoLabel.text = [itemData objectFormatStringForKey:@"浇筑方式" defaults:@"未知"];
        cell.ffzdLabel.text = [itemData objectFormatStringForKey:@"实际分发站" defaults:@"未知"];
        cell.jhflLabel.text = [itemData objectFormatFloatStringForKey:@"计划方量" retain:1 format:@"%@方"];
        
    } else if(indexPath.row == 2){
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.copysOrderButton.tag = indexPath.section;
        cell.changeButton.tag = indexPath.section;
        [cell.copysOrderButton addTarget:self action:@selector(copyOrderSelector:) forControlEvents:UIControlEventTouchUpInside];
        
        //@订单状态（0未审核，1已审核, 2已拒绝）
        NSInteger sfsh = [itemData objectFormatIntegerForKey:@"DDZT"];
        if (sfsh == 1) {
            NSInteger fffl = [itemData objectFormatIntegerForKey:@"发货方量"];
            NSInteger ffcc = [itemData objectFormatIntegerForKey:@"发货车次"];
            if(ffcc>0) cell.orderManyLabel.text = [NSString stringWithFormat:@"累计发货%ld方，已发%ld车",fffl,ffcc];
            else cell.orderManyLabel.text = @"正等待发货";
            
            [cell.changeButton setTitle:@"物流追踪" forState:UIControlStateNormal];
            [cell.changeButton addTarget:self action:@selector(logisticsOrderSelector:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            cell.changeButton.hidden = YES;
            cell.orderManyLabel.text= @"";
        }
    }
    
    return cell;
}


#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 10;
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) return 30;
    if(indexPath.row == 1) return 100;
    if(indexPath.row == 2) return 36;
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.section];
    
    OMOrderDetailsViewController *mOrderDetails = [[OMOrderDetailsViewController alloc] initWithValue:itemData];
    mOrderDetails.backResultDelagate = self;
    [self.navigationController pushViewController:mOrderDetails animated:YES];
}

#pragma mark
#pragma mark - IBAction Button Event

- (void)copyOrderSelector:(UIButton*)selector
{
    //复制下单
    NSDictionary *orderInfo = [self.resultData objectAtIndex:selector.tag];
    OMCreateOrderViewController *viewController = [[OMCreateOrderViewController alloc] initWithValue:orderInfo];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)logisticsOrderSelector:(UIButton*)selector
{
    //物流信息
    NSDictionary *orderInfo = [self.resultData objectAtIndex:selector.tag];
    OMLogisticsInfoViewController *viewController = [[OMLogisticsInfoViewController alloc] initWithValue:orderInfo];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark
#pragma mark - BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if([key isEqualToString:@"ReloadOrder"]){
        [self.tableView headerBeginRefreshing];
        
    } else if([key isEqualToString:@"SerachOrder"]){
        //订单搜索
        NSArray *searchArray = backValue;
        self.searchText = searchArray[0];
        self.searchStartTime = searchArray[1];
        self.searchStopTime = searchArray[2];
        
        [self.resultData removeAllObjects];
        [self.tableView reloadData];
        [self.tableView headerBeginRefreshing];
        
    } else if([key isEqualToString:@"ReceiveOrder"]){
        //订单接单
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index < self.resultData.count){
            [self.resultData removeObjectAtIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无订单" isShow:YES];
        
    } else if (backValue && [backValue isKindOfClass:[NSArray class]]) {
        //标记订单为已读
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if (index < self.resultData.count) {
            //设置UIsegmentedControl的Badge显示
            //@审核状态（0未审核，1已审核, 2已拒绝，3已作废，4待接单), 此处与UIsegmentedControl的selectIndex相同
            NSDictionary *itemData = originalArray[0];
            NSInteger segmentedControl = 0;
            NSInteger DDZTInt = [itemData objectFormatIntegerForKey:@"DDZT"];
            if(DDZTInt == 0) segmentedControl = 0;
            if(DDZTInt == 1) segmentedControl = 1;
            if(DDZTInt == 2) segmentedControl = 2;
            
            NSInteger barge = [self.segmentedControl getBadgeNumberForSegmentAtIndex:segmentedControl];
            barge = barge > 0 ? barge-1 : 0;
            [self.segmentedControl setBadgeNumber:barge forSegmentAtIndex:segmentedControl];
            
            //移除并重新添加
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
            [self.tableView reloadData];
            
        }
    }
}

@end
